 /*
  * Team Java
  * This is the Memory for threads to use.
  * Author(s): Michael Satran Jr, Michael Pogson, Stephen Hunter
  * Date: 5/31/2012
  */

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "memory.h"


int global_var = 0;
int isReady = 0;
pthread_mutex_t global_mutex;
pthread_mutex_t write_mutex; 
pthread_mutex_t read_mutex;
pthread_mutex_t thread_mutex; 

void memstart() {

	pthread_mutex_init(&global_mutex, NULL);
	pthread_mutex_init(&read_mutex, NULL);
	pthread_mutex_init(&write_mutex, NULL);
	pthread_mutex_init(&thread_mutex, NULL);

}

void *memWrite() {
	
	pthread_mutex_trylock(&write_mutex);
	pthread_mutex_trylock(&read_mutex);
	pthread_mutex_trylock(&global_mutex);
	global_var++;
	int i = 0;
	while(i < 1000000) {
		i++;
	}
	pthread_mutex_unlock(&global_mutex);
	pthread_mutex_unlock(&read_mutex);
	pthread_mutex_unlock(&write_mutex);
}

void *memRead() {
	
	pthread_mutex_trylock(&read_mutex);
	pthread_mutex_trylock(&write_mutex);
	pthread_mutex_trylock(&global_mutex);
	printf("Reading count, count is: %d\n", global_var);
			int i = 0;
	while(i < 10000000) {
		i++;
	}
	pthread_mutex_unlock(&global_mutex);
	pthread_mutex_unlock(&write_mutex);
	pthread_mutex_unlock(&read_mutex);
}

void *mutexAcquire() {
	
	pthread_mutex_trylock(&thread_mutex);
	int i = 0;
	while(i < 100000) {
		i++;
	}
}

void *mutexGive() {


	pthread_mutex_unlock(&thread_mutex);
		int i = 0;
	while(i < 10000) {
		i++;
	}

}